<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>苏州旅行助手 - 高德地图版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: #f0f9ff;
            overflow: hidden;
        }
        
        .map-container {
            position: relative;
            width: 100vw;
            height: 100vh;
        }
        
        #mapContainer {
            width: 100%;
            height: 100vh;
            margin-top: 60px;
            margin-bottom: 60px;
        }
        
        .info-panel {
            position: absolute;
            top: 20px;
            left: 20px;
            right: 20px;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }
        
        .header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            padding: 8px 20px;
            z-index: 1000;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
            transition: all 0.3s ease;
        }
        
        .header.collapsed {
            transform: translateY(-100%);
        }
        
        .header-left {
            display: flex;
            align-items: center;
            gap: 16px;
        }
        
        .title {
            font-size: 16px;
            font-weight: bold;
            color: #0ea5e9;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .subtitle {
            font-size: 10px;
            color: #6b7280;
            margin: 0;
        }
        
        .header-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .header-toggle {
            background: rgba(14, 165, 233, 0.1);
            border: 1px solid #0ea5e9;
            border-radius: 6px;
            padding: 4px 8px;
            font-size: 12px;
            color: #0ea5e9;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .header-toggle:hover {
            background: #0ea5e9;
            color: white;
        }
        
        .current-info {
            background: #f0f9ff;
            border: 1px solid #0ea5e9;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 12px;
        }
        
        .current-title {
            font-size: 14px;
            font-weight: 600;
            color: #0369a1;
            margin-bottom: 4px;
        }
        
        .current-desc {
            font-size: 12px;
            color: #0284c7;
        }
        
        .weather-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #fef3c7;
            border: 1px solid #f59e0b;
            border-radius: 8px;
            padding: 8px 12px;
        }
        
        .weather-temp {
            font-size: 18px;
            font-weight: bold;
            color: #92400e;
        }
        
        .weather-desc {
            font-size: 12px;
            color: #a16207;
        }
        
        .timeline {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            padding: 8px 20px;
            box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            transition: all 0.3s ease;
            overflow-x: auto;
            overflow-y: hidden;
        }
        
        .timeline.collapsed {
            transform: translateY(100%);
        }
        
        .timeline-container {
            display: flex;
            align-items: center;
            gap: 16px;
            min-width: max-content;
        }
        
        .timeline-title {
            font-size: 12px;
            font-weight: 600;
            color: #374151;
            white-space: nowrap;
            margin-right: 8px;
        }
        
        .timeline-item {
            display: flex;
            align-items: center;
            padding: 6px 12px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.2s;
            white-space: nowrap;
            border: 1px solid rgba(14, 165, 233, 0.2);
            min-width: max-content;
        }
        
        .timeline-item:hover {
            background: rgba(14, 165, 233, 0.1);
            border-color: #0ea5e9;
            transform: translateY(-2px);
        }
        
        .timeline-time {
            font-size: 10px;
            font-weight: 600;
            color: #6b7280;
            margin-right: 8px;
        }
        
        .timeline-content {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .timeline-title-text {
            font-size: 11px;
            font-weight: 500;
            color: #374151;
        }
        
        .timeline-desc {
            font-size: 10px;
            color: #6b7280;
            max-width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .timeline-item.current {
            background: rgba(14, 165, 233, 0.1);
            border-color: #0ea5e9;
        }
        
        .timeline-item.current .timeline-time {
            color: #0ea5e9;
        }
        
        .timeline-item.current .timeline-title-text {
            color: #0ea5e9;
        }
        
        .timeline-item.completed {
            opacity: 0.6;
        }
        
        .timeline-toggle {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: rgba(14, 165, 233, 0.1);
            border: 1px solid #0ea5e9;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
            z-index: 1001;
        }
        
        .timeline-toggle:hover {
            background: #0ea5e9;
            color: white;
        }
        
        .controls {
            position: absolute;
            top: 20px;
            right: 20px;
            z-index: 1001;
        }
        
        .control-btn {
            width: 40px;
            height: 40px;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            margin-bottom: 8px;
            transition: all 0.3s ease;
        }
        
        .control-btn:hover {
            transform: scale(1.1);
            background: white;
        }
        
        .loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: #6b7280;
            z-index: 1002;
        }
        
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f4f6;
            border-top: 4px solid #0ea5e9;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 16px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="map-container">
        <!-- 加载提示 -->
        <div class="loading" id="loading">
            <div class="loading-spinner"></div>
            <div>正在加载高德地图...</div>
        </div>
        
        <!-- 地图容器 -->
        <div id="mapContainer"></div>
        
        <!-- 头部 -->
        <div class="header" id="header">
            <div class="header-left">
                <h1 class="title">🗺️ 苏州旅行助手</h1>
                <div class="subtitle">高德地图版 · 实时行程跟踪</div>
            </div>
            <div class="header-right">
                <div class="current-info">
                    <div class="current-title">📍 当前行程</div>
                    <div class="current-desc" id="currentDesc">正在加载行程信息...</div>
                </div>
                <div class="weather-info">
                    <div class="weather-temp" id="weatherTemp">🌤️ 加载中...</div>
                    <div class="weather-desc" id="weatherDesc">苏州</div>
                </div>
                <button class="header-toggle" onclick="toggleHeader()">收起</button>
            </div>
        </div>
        
        <!-- 控制按钮 -->
        <div class="controls">
            <button class="control-btn" onclick="toggleTimeline()" title="切换时间轴">📅</button>
            <button class="control-btn" onclick="refreshWeather()" title="刷新天气">🌤️</button>
            <button class="control-btn" onclick="centerMap()" title="居中地图">🎯</button>
            <button class="control-btn" onclick="toggleAddMode()" title="添加途经点">➕</button>
        </div>
        
        <!-- 时间轴 -->
        <div class="timeline" id="timeline">
            <div class="timeline-container">
                <div class="timeline-title">📅 行程时间轴</div>
            
            <div class="timeline-item completed" data-location="苏州站" data-time="14:01">
                <div class="timeline-time">14:01</div>
                <div class="timeline-content">
                    <div class="timeline-title-text">高铁抵达苏州</div>
                    <div class="timeline-desc">苏州站</div>
                </div>
            </div>
            
            <div class="timeline-item completed" data-location="宜必思酒店" data-time="14:30">
                <div class="timeline-time">14:30</div>
                <div class="timeline-content">
                    <div class="timeline-title-text">宜必思酒店放行李</div>
                    <div class="timeline-desc">乐桥店</div>
                </div>
            </div>
            
            <div class="timeline-item completed" data-location="伟记面馆" data-time="16:40">
                <div class="timeline-time">16:40</div>
                <div class="timeline-content">
                    <div class="timeline-title-text">伟记吃面</div>
                    <div class="timeline-desc">品尝苏州特色面条</div>
                </div>
            </div>
            
            <div class="timeline-item current" data-location="拙政园" data-time="17:10">
                <div class="timeline-time">17:10</div>
                <div class="timeline-content">
                    <div class="timeline-title-text">拙政园游览</div>
                    <div class="timeline-desc">苏州最著名的古典园林</div>
                </div>
            </div>
            
            <div class="timeline-item" data-location="平江路" data-time="18:50">
                <div class="timeline-time">18:50</div>
                <div class="timeline-content">
                    <div class="timeline-title-text">平江路夜游</div>
                    <div class="timeline-desc">历史文化街区</div>
                </div>
            </div>
            
            <div class="timeline-item" data-location="宜必思酒店" data-time="21:00">
                <div class="timeline-time">21:00</div>
                <div class="timeline-content">
                    <div class="timeline-title-text">返回酒店休息</div>
                    <div class="timeline-desc">宜必思酒店</div>
                </div>
            </div>
            </div>
        </div>
        
        <!-- 时间轴切换按钮 -->
        <div class="timeline-toggle" onclick="toggleTimeline()" title="切换时间轴">
            📅
        </div>
    </div>

    <!-- 高德地图 API -->
    <script src="https://webapi.amap.com/maps?v=2.0&key=自己的Key&callback=initMap"></script>
    <script src="config.js"></script>
    <script src="database.js"></script>
    
    <script>
        // 高德地图实例
        let map;
        let markers = [];
        
        // 行程地点数据
        const itineraryData = [
            {
                id: 1,
                name: '苏州站',
                time: '14:01',
                description: '乘坐高铁抵达苏州站，准备开始苏州之旅',
                coordinates: [120.5853, 31.2989],
                type: 'arrival',
                status: 'completed'
            },
            {
                id: 2,
                name: '宜必思酒店',
                time: '14:30',
                description: '前往酒店办理入住，放置行李',
                coordinates: [120.6186, 31.3108],
                type: 'hotel',
                status: 'completed'
            },
            {
                id: 3,
                name: '伟记面馆',
                time: '16:40',
                description: '品尝苏州特色面条，体验当地美食文化',
                coordinates: [120.6186, 31.3108],
                type: 'meal',
                status: 'completed'
            },
            {
                id: 4,
                name: '拙政园',
                time: '17:10',
                description: '游览苏州最著名的古典园林，感受江南园林之美',
                coordinates: [120.6254, 31.3256],
                type: 'attraction',
                status: 'current'
            },
            {
                id: 5,
                name: '平江路',
                time: '18:50',
                description: '漫步平江路历史文化街区，体验苏州古城的夜生活',
                coordinates: [120.6300, 31.3200],
                type: 'attraction',
                status: 'pending'
            },
            {
                id: 6,
                name: '宜必思酒店',
                time: '21:00',
                description: '结束第一天的行程，返回酒店休息',
                coordinates: [120.6186, 31.3108],
                type: 'hotel',
                status: 'pending'
            },
            {
                id: 7,
                name: '旺山景区',
                time: '08:30',
                description: '8公里徒步环线：茶园-九龙潭-乾元寺-叆叇岭-钱家坞',
                coordinates: [120.4500, 31.2000],
                type: 'hiking',
                status: 'pending'
            }
        ];
        
        // 地图初始化
        async function initMap() {
            try {
                // 检查必要的依赖
                if (typeof window.AppConfig === 'undefined') {
                    throw new Error('配置文件未加载');
                }
                
                if (typeof window.dbManager === 'undefined') {
                    throw new Error('数据库管理器未加载');
                }
                
                // 初始化数据库
                await window.dbManager.init();
                console.log('数据库初始化完成');
                
                // 隐藏加载提示
                document.getElementById('loading').style.display = 'none';
                
                // 使用配置文件创建地图实例
                const config = window.AppConfig.amap;
                map = new AMap.Map('mapContainer', {
                    zoom: config.zoom,
                    center: config.center,
                    mapStyle: config.mapStyle
                });
                
                console.log('地图初始化完成');
                
                // 加载行程数据
                await loadItineraryData();
                
                // 添加地点标记
                addItineraryMarkers();
                
                // 添加地图点击事件监听（用于POI搜索）
                map.on('click', onMapClickForPOI);
                
                // 获取天气信息
                getWeatherInfo();
                
                // 更新当前时间
                updateCurrentTime();
                setInterval(updateCurrentTime, 1000);
                
                // 加载路线管理界面
                loadRouteManagement();
                
                console.log('应用初始化完成');
                
            } catch (error) {
                console.error('初始化失败:', error);
                
                // 隐藏加载提示
                document.getElementById('loading').style.display = 'none';
                
                // 显示错误信息
                const errorDiv = document.createElement('div');
                errorDiv.style.cssText = `
                    position: fixed;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    background: #ef4444;
                    color: white;
                    padding: 20px;
                    border-radius: 8px;
                    text-align: center;
                    z-index: 10000;
                    max-width: 400px;
                `;
                errorDiv.innerHTML = `
                    <h3 style="margin: 0 0 10px 0;">❌ 初始化失败</h3>
                    <p style="margin: 0 0 15px 0;">${error.message}</p>
                    <button onclick="location.reload()" style="
                        background: white;
                        color: #ef4444;
                        border: none;
                        padding: 8px 16px;
                        border-radius: 4px;
                        cursor: pointer;
                        font-weight: 600;
                    ">刷新页面</button>
                `;
                document.body.appendChild(errorDiv);
            }
        }
        
        // 添加行程地点标记
        function addItineraryMarkers() {
            itineraryData.forEach((item, index) => {
                // 创建自定义标记内容
                const markerContent = createMarkerContent(item, index + 1);
                
                // 创建标记
                const marker = new AMap.Marker({
                    position: item.coordinates,
                    content: markerContent,
                    title: item.name
                });
                
                // 添加点击事件
                marker.on('click', function() {
                    showLocationInfo(item);
                });
                
                // 添加到地图
                marker.setMap(map);
                markers.push(marker);
            });
            
            // 添加路线
            addRouteLines();
        }
        
        // 创建标记内容
        function createMarkerContent(item, number) {
            const colors = {
                arrival: '#10b981',
                hotel: '#3b82f6',
                meal: '#f59e0b',
                attraction: '#8b5cf6',
                hiking: '#06b6d4',
                departure: '#6b7280'
            };
            
            const color = colors[item.type] || '#0ea5e9';
            const statusClass = item.status === 'current' ? 'current' : 
                               item.status === 'completed' ? 'completed' : '';
            
            // 添加类型图标
            const typeIcons = {
                arrival: '🚄',
                hotel: '🏨',
                meal: '🍜',
                attraction: '🏛️',
                hiking: '🥾',
                departure: '🚄'
            };
            
            const icon = typeIcons[item.type] || '📍';
            
            return `
                <div style="
                    width: 50px;
                    height: 50px;
                    background: white;
                    border: 3px solid ${color};
                    border-radius: 50%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    font-weight: bold;
                    font-size: 12px;
                    color: ${color};
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                    cursor: pointer;
                    transition: all 0.3s ease;
                    position: relative;
                    ${item.status === 'current' ? 'animation: pulse 2s infinite;' : ''}
                " onmouseover="this.style.transform='scale(1.2); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25)'" 
                   onmouseout="this.style.transform='scale(1); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15)'"
                   onclick="showLocationDetails('${item.name}', ${JSON.stringify(item).replace(/"/g, '&quot;')})">
                    <div style="font-size: 16px; margin-bottom: 2px;">${icon}</div>
                    <div style="font-size: 10px; font-weight: bold;">${number}</div>
                    ${item.status === 'current' ? '<div style="position: absolute; top: -5px; right: -5px; width: 12px; height: 12px; background: #ef4444; border-radius: 50%; border: 2px solid white;"></div>' : ''}
                </div>
            `;
        }
        
        // 添加路线
        function addRouteLines() {
            // 为每两个相邻地点之间添加路线
            for (let i = 0; i < itineraryData.length - 1; i++) {
                const startItem = itineraryData[i];
                const endItem = itineraryData[i + 1];
                
                // 异步获取真实路线路径
                getRealRoutePath(startItem.coordinates, endItem.coordinates, startItem, endItem);
            }
        }
        
        // 路线规划相关变量
        let currentRoutePlan = null;
        let routeHistory = [];
        
        // 获取真实路线路径
        async function getRealRoutePath(origin, destination, startItem, endItem) {
            try {
                // 优先获取驾车路线作为主要路线显示
                const drivingUrl = `https://restapi.amap.com/v3/direction/driving?origin=${origin[0]},${origin[1]}&destination=${destination[0]},${destination[1]}&key=自己的Key&extensions=base`;
                const response = await fetch(drivingUrl);
                const data = await response.json();
                
                let path = [origin, destination]; // 默认直线
                
                if (data.status === '1' && data.route && data.route.paths && data.route.paths.length > 0) {
                    const drivingPath = data.route.paths[0];
                    if (drivingPath.steps && drivingPath.steps.length > 0) {
                        // 使用驾车路线的路径点
                        path = [];
                        drivingPath.steps.forEach(step => {
                            if (step.polyline) {
                                const coords = step.polyline.split(';').map(coord => {
                                    const [lng, lat] = coord.split(',');
                                    return [parseFloat(lng), parseFloat(lat)];
                                });
                                path = path.concat(coords);
                            }
                        });
                    }
                }
                
                // 创建路线
                const polyline = new AMap.Polyline({
                    path: path,
                    strokeColor: '#0ea5e9',
                    strokeWeight: 4,
                    strokeOpacity: 0.7,
                    strokeStyle: 'solid',
                    cursor: 'pointer'
                });
                
                // 添加悬停效果
                polyline.on('mouseover', function() {
                    polyline.setOptions({
                        strokeWeight: 6,
                        strokeOpacity: 0.9,
                        strokeColor: '#10b981'
                    });
                    showRouteInfo(startItem, endItem, polyline);
                });
                
                polyline.on('mouseout', function() {
                    polyline.setOptions({
                        strokeWeight: 4,
                        strokeOpacity: 0.7,
                        strokeColor: '#0ea5e9'
                    });
                    hideRouteInfo();
                });
                
                // 添加双击事件监听
                polyline.on('dblclick', function(e) {
                    showAddWaypointDialog(e.lnglat, startItem, endItem);
                });
                
                polyline.setMap(map);
                
            } catch (error) {
                console.error('获取路线路径失败:', error);
                // 如果获取失败，使用直线
                const polyline = new AMap.Polyline({
                    path: [origin, destination],
                    strokeColor: '#0ea5e9',
                    strokeWeight: 4,
                    strokeOpacity: 0.7,
                    strokeStyle: 'solid',
                    cursor: 'pointer'
                });
                
                polyline.on('mouseover', function() {
                    polyline.setOptions({
                        strokeWeight: 6,
                        strokeOpacity: 0.9,
                        strokeColor: '#10b981'
                    });
                    showRouteInfo(startItem, endItem, polyline);
                });
                
                polyline.on('mouseout', function() {
                    polyline.setOptions({
                        strokeWeight: 4,
                        strokeOpacity: 0.7,
                        strokeColor: '#0ea5e9'
                    });
                    hideRouteInfo();
                });
                
                polyline.setMap(map);
            }
        }
        
        // 显示地点详细信息
        function showLocationDetails(name, item) {
            // 创建模态框
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                padding: 20px;
            `;
            
            const typeIcons = {
                arrival: '🚄',
                hotel: '🏨',
                meal: '🍜',
                attraction: '🏛️',
                hiking: '🥾',
                departure: '🚄'
            };
            
            const typeNames = {
                arrival: '交通',
                hotel: '住宿',
                meal: '用餐',
                attraction: '景点',
                hiking: '徒步',
                departure: '交通'
            };
            
            const colors = {
                arrival: '#10b981',
                hotel: '#3b82f6',
                meal: '#f59e0b',
                attraction: '#8b5cf6',
                hiking: '#06b6d4',
                departure: '#6b7280'
            };
            
            const color = colors[item.type] || '#0ea5e9';
            const icon = typeIcons[item.type] || '📍';
            const typeName = typeNames[item.type] || '地点';
            
            modal.innerHTML = `
                <div style="
                    background: white;
                    border-radius: 16px;
                    padding: 24px;
                    max-width: 400px;
                    width: 100%;
                    max-height: 80vh;
                    overflow-y: auto;
                    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
                    position: relative;
                ">
                    <button onclick="this.closest('.modal').remove()" style="
                        position: absolute;
                        top: 16px;
                        right: 16px;
                        background: #f3f4f6;
                        border: none;
                        width: 32px;
                        height: 32px;
                        border-radius: 50%;
                        cursor: pointer;
                        font-size: 18px;
                        color: #6b7280;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    ">×</button>
                    
                    <div style="text-align: center; margin-bottom: 20px;">
                        <div style="font-size: 48px; margin-bottom: 8px;">${icon}</div>
                        <h2 style="margin: 0 0 4px 0; color: #1f2937; font-size: 20px;">${item.name}</h2>
                        <div style="
                            display: inline-block;
                            background: ${color};
                            color: white;
                            padding: 4px 12px;
                            border-radius: 20px;
                            font-size: 12px;
                            font-weight: 600;
                        ">${typeName}</div>
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <div style="display: flex; align-items: center; margin-bottom: 12px;">
                            <span style="font-size: 16px; margin-right: 8px;">⏰</span>
                            <span style="font-size: 16px; font-weight: 600; color: #1f2937;">${item.time}</span>
                        </div>
                        <div style="display: flex; align-items: flex-start; margin-bottom: 12px;">
                            <span style="font-size: 16px; margin-right: 8px; margin-top: 2px;">📍</span>
                            <span style="font-size: 14px; color: #6b7280; line-height: 1.5;">${item.description}</span>
                        </div>
                        <div style="display: flex; align-items: center; margin-bottom: 12px;">
                            <span style="font-size: 16px; margin-right: 8px;">🎯</span>
                            <span style="font-size: 14px; color: #6b7280;">坐标: ${item.coordinates[0].toFixed(6)}, ${item.coordinates[1].toFixed(6)}</span>
                        </div>
                        <div style="display: flex; align-items: center;">
                            <span style="font-size: 16px; margin-right: 8px;">📊</span>
                            <span style="font-size: 14px; color: #6b7280;">状态: ${item.status === 'current' ? '进行中' : item.status === 'completed' ? '已完成' : '待开始'}</span>
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 12px;">
                        <button onclick="navigateToLocation('${item.name}'); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #0ea5e9;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 8px;
                        ">
                            🗺️ 导航
                        </button>
                        <button onclick="centerOnLocation('${item.name}'); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #10b981;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 8px;
                        ">
                            🎯 居中
                        </button>
                    </div>
                </div>
            `;
            
            modal.className = 'modal';
            document.body.appendChild(modal);
            
            // 点击背景关闭
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        }
        
        // 显示地点信息（简化版）
        function showLocationInfo(item) {
            showLocationDetails(item.name, item);
        }
        
        // 导航到指定地点
        function navigateToLocation(locationName) {
            const item = itineraryData.find(item => item.name === locationName);
            if (item) {
                const url = `https://uri.amap.com/navigation?to=${item.coordinates[0]},${item.coordinates[1]}&name=${encodeURIComponent(locationName)}&src=苏州旅行助手`;
                window.open(url, '_blank');
            }
        }
        
        // 居中到指定地点
        function centerOnLocation(locationName) {
            const item = itineraryData.find(item => item.name === locationName);
            if (item) {
                map.setCenter(item.coordinates);
                map.setZoom(16);
            }
        }
        
        // 路线信息显示相关变量
        let routeInfoWindow = null;
        let currentRouteData = null;
        
        // 添加途经点相关变量
        let isAddMode = false;
        let customMarkers = [];
        let customItinerary = [];
        
        // 显示路线信息
        function showRouteInfo(startItem, endItem, polyline) {
            // 移除之前的路线信息窗口
            if (routeInfoWindow) {
                routeInfoWindow.close();
            }
            
            // 创建路线信息内容
            const content = createRouteInfoContent(startItem, endItem);
            
            // 创建信息窗口
            routeInfoWindow = new AMap.InfoWindow({
                content: content,
                offset: new AMap.Pixel(0, -10),
                isCustom: true
            });
            
            // 计算路线中点
            const midPoint = [
                (startItem.coordinates[0] + endItem.coordinates[0]) / 2,
                (startItem.coordinates[1] + endItem.coordinates[1]) / 2
            ];
            
            routeInfoWindow.open(map, midPoint);
            
            // 异步获取路线规划数据
            getRoutePlanningData(startItem, endItem);
        }
        
        // 隐藏路线信息
        function hideRouteInfo() {
            if (routeInfoWindow) {
                routeInfoWindow.close();
                routeInfoWindow = null;
            }
        }
        
        // 创建路线信息内容
        function createRouteInfoContent(startItem, endItem) {
            return `
                <div style="
                    background: white;
                    border-radius: 12px;
                    padding: 16px;
                    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
                    min-width: 280px;
                    max-width: 320px;
                ">
                    <div style="text-align: center; margin-bottom: 12px;">
                        <div style="font-size: 16px; font-weight: 600; color: #1f2937; margin-bottom: 4px;">
                            ${startItem.name} → ${endItem.name}
                        </div>
                        <div style="font-size: 12px; color: #6b7280;">
                            ${startItem.time} - ${endItem.time}
                        </div>
                    </div>
                    
                    <div id="routeInfoContent" style="text-align: center; color: #6b7280; font-size: 14px;">
                        <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 8px;">
                            <div style="width: 20px; height: 20px; border: 2px solid #0ea5e9; border-radius: 50%; margin-right: 8px; animation: spin 1s linear infinite;"></div>
                            正在规划路线...
                        </div>
                    </div>
                </div>
            `;
        }
        
        // 获取路线规划数据
        async function getRoutePlanningData(startItem, endItem) {
            try {
                // 并行获取步行、骑行、公交、地铁、驾车路线规划
                const [walkingData, cyclingData, transitData, subwayData, drivingData] = await Promise.allSettled([
                    getWalkingRoute(startItem.coordinates, endItem.coordinates),
                    getCyclingRoute(startItem.coordinates, endItem.coordinates),
                    getTransitRoute(startItem.coordinates, endItem.coordinates),
                    getSubwayRoute(startItem.coordinates, endItem.coordinates),
                    getDrivingRoute(startItem.coordinates, endItem.coordinates)
                ]);
                
                // 更新路线信息显示
                updateRouteInfoDisplay(startItem, endItem, {
                    walking: walkingData.status === 'fulfilled' ? walkingData.value : null,
                    cycling: cyclingData.status === 'fulfilled' ? cyclingData.value : null,
                    transit: transitData.status === 'fulfilled' ? transitData.value : null,
                    subway: subwayData.status === 'fulfilled' ? subwayData.value : null,
                    driving: drivingData.status === 'fulfilled' ? drivingData.value : null
                });
                
            } catch (error) {
                console.error('获取路线规划数据失败:', error);
                updateRouteInfoDisplay(startItem, endItem, null, '获取路线信息失败');
            }
        }
        
        // 获取步行路线规划
        async function getWalkingRoute(origin, destination) {
            const url = `https://restapi.amap.com/v3/direction/walking?origin=${origin[0]},${origin[1]}&destination=${destination[0]},${destination[1]}&key=自己的Key`;
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.status === '1' && data.route && data.route.paths && data.route.paths.length > 0) {
                const path = data.route.paths[0];
                return {
                    type: 'walking',
                    distance: path.distance,
                    duration: path.duration,
                    cost: 0,
                    icon: '🚶',
                    name: '步行',
                    steps: path.steps || []
                };
            }
            return null;
        }
        
        // 获取公交路线规划
        async function getTransitRoute(origin, destination) {
            const url = `https://restapi.amap.com/v3/direction/transit/integrated?origin=${origin[0]},${origin[1]}&destination=${destination[0]},${destination[1]}&city=苏州&strategy=0&extensions=all&key=自己的Key`;
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.status === '1' && data.route && data.route.transits && data.route.transits.length > 0) {
                const transit = data.route.transits[0];
                
                // 检查是否包含地铁
                const hasSubway = transit.segments && transit.segments.some(segment => 
                    segment.bus && segment.bus.type && segment.bus.type.includes('地铁')
                );
                
                return {
                    type: 'transit',
                    distance: transit.walking_distance || 0,
                    duration: transit.duration,
                    cost: transit.cost || 0,
                    icon: hasSubway ? '🚇' : '🚌',
                    name: hasSubway ? '地铁' : '公交',
                    segments: transit.segments || []
                };
            }
            return null;
        }
        
        // 获取骑行路线规划
        async function getCyclingRoute(origin, destination) {
            const url = `https://restapi.amap.com/v4/direction/bicycling?origin=${origin[0]},${origin[1]}&destination=${destination[0]},${destination[1]}&key=自己的Key`;
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.errcode === 0 && data.data && data.data.paths && data.data.paths.length > 0) {
                const path = data.data.paths[0];
                return {
                    type: 'cycling',
                    distance: path.distance,
                    duration: path.duration,
                    cost: 0,
                    icon: '🚴',
                    name: '骑行',
                    steps: path.steps || []
                };
            }
            return null;
        }
        
        // 获取地铁路线规划
        async function getSubwayRoute(origin, destination) {
            const url = `https://restapi.amap.com/v3/direction/transit/integrated?origin=${origin[0]},${origin[1]}&destination=${destination[0]},${destination[1]}&city=苏州&strategy=0&extensions=all&key=自己的Key`;
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.status === '1' && data.route && data.route.transits && data.route.transits.length > 0) {
                // 查找包含地铁的方案
                const subwayTransit = data.route.transits.find(transit => 
                    transit.segments && transit.segments.some(segment => 
                        segment.bus && segment.bus.buslines && segment.bus.buslines.some(busline => 
                            busline.type && busline.type.includes('地铁')
                        )
                    )
                );
                
                if (subwayTransit) {
                    return {
                        type: 'subway',
                        distance: subwayTransit.walking_distance || 0,
                        duration: subwayTransit.duration,
                        cost: subwayTransit.cost || 0,
                        icon: '🚇',
                        name: '地铁',
                        segments: subwayTransit.segments || []
                    };
                }
            }
            return null;
        }
        
        // 获取驾车路线规划
        async function getDrivingRoute(origin, destination) {
            const url = `https://restapi.amap.com/v3/direction/driving?origin=${origin[0]},${origin[1]}&destination=${destination[0]},${destination[1]}&key=自己的Key&extensions=all`;
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.status === '1' && data.route && data.route.paths && data.route.paths.length > 0) {
                const path = data.route.paths[0];
                return {
                    type: 'driving',
                    distance: path.distance,
                    duration: path.duration,
                    cost: path.tolls || 0,
                    icon: '🚗',
                    name: '驾车',
                    steps: path.steps || []
                };
            }
            return null;
        }
        
        // 更新路线信息显示
        function updateRouteInfoDisplay(startItem, endItem, routeData, error = null) {
            const contentElement = document.getElementById('routeInfoContent');
            if (!contentElement) return;
            
            if (error) {
                contentElement.innerHTML = `
                    <div style="color: #ef4444; font-size: 14px;">
                        ❌ ${error}
                    </div>
                `;
                return;
            }
            
            if (!routeData) {
                contentElement.innerHTML = `
                    <div style="color: #6b7280; font-size: 14px;">
                        ⚠️ 无法获取路线信息
                    </div>
                `;
                return;
            }
            
            let html = '<div style="display: flex; flex-direction: column; gap: 8px;">';
            
            // 步行信息
            if (routeData.walking) {
                html += createRouteItem(routeData.walking);
            }
            
            // 骑行信息
            if (routeData.cycling) {
                html += createRouteItem(routeData.cycling);
            }
            
            // 地铁信息（优先显示）
            if (routeData.subway) {
                html += createRouteItem(routeData.subway);
            }
            
            // 公交信息
            if (routeData.transit) {
                html += createRouteItem(routeData.transit);
            }
            
            // 驾车信息
            if (routeData.driving) {
                html += createRouteItem(routeData.driving);
            }
            
            html += '</div>';
            contentElement.innerHTML = html;
        }
        
        // 创建路线项目
        function createRouteItem(route) {
            const distance = formatDistance(route.distance);
            const duration = formatDuration(route.duration);
            const cost = route.cost > 0 ? `¥${route.cost}` : '免费';
            
            return `
                <div style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 8px 12px;
                    background: #f8fafc;
                    border-radius: 8px;
                    border: 1px solid #e2e8f0;
                ">
                    <div style="display: flex; align-items: center;">
                        <span style="font-size: 18px; margin-right: 8px;">${route.icon}</span>
                        <span style="font-size: 14px; font-weight: 600; color: #374151;">${route.name}</span>
                    </div>
                    <div style="text-align: right; font-size: 12px; color: #6b7280;">
                        <div>${distance}</div>
                        <div>${duration}</div>
                        <div style="color: #10b981; font-weight: 600;">${cost}</div>
                    </div>
                </div>
            `;
        }
        
        // 格式化距离
        function formatDistance(distance) {
            if (distance < 1000) {
                return `${distance}米`;
            } else {
                return `${(distance / 1000).toFixed(1)}公里`;
            }
        }
        
        // 格式化时间
        function formatDuration(duration) {
            const hours = Math.floor(duration / 3600);
            const minutes = Math.floor((duration % 3600) / 60);
            
            if (hours > 0) {
                return `${hours}小时${minutes}分钟`;
            } else {
                return `${minutes}分钟`;
            }
        }
        
        // 切换添加模式
        function toggleAddMode() {
            isAddMode = !isAddMode;
            const addBtn = document.querySelector('.control-btn[onclick="toggleAddMode()"]');
            
            if (isAddMode) {
                addBtn.style.background = '#10b981';
                addBtn.style.color = 'white';
                addBtn.title = '点击地图添加途经点 (点击按钮退出)';
                
                // 添加地图点击事件
                map.on('click', onMapClick);
                
                // 显示提示
                showAddModeTip();
            } else {
                addBtn.style.background = 'rgba(255, 255, 255, 0.9)';
                addBtn.style.color = '#6b7280';
                addBtn.title = '添加途经点';
                
                // 移除地图点击事件
                map.off('click', onMapClick);
                
                // 隐藏提示
                hideAddModeTip();
            }
        }
        
        // 地图点击事件
        function onMapClick(e) {
            if (!isAddMode) return;
            
            const lng = e.lnglat.lng;
            const lat = e.lnglat.lat;
            
            // 显示添加途经点对话框
            showAddPointDialog(lng, lat);
        }
        
        // 显示添加模式提示
        function showAddModeTip() {
            const tip = document.createElement('div');
            tip.id = 'addModeTip';
            tip.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 16px 24px;
                border-radius: 8px;
                font-size: 14px;
                z-index: 10000;
                text-align: center;
                max-width: 300px;
            `;
            tip.innerHTML = `
                <div style="margin-bottom: 8px;">📍 添加途经点模式</div>
                <div style="font-size: 12px; color: #ccc;">点击地图上的任意位置添加新的途经点</div>
            `;
            document.body.appendChild(tip);
            
            // 3秒后自动隐藏
            setTimeout(() => {
                if (tip.parentNode) {
                    tip.parentNode.removeChild(tip);
                }
            }, 3000);
        }
        
        // 隐藏添加模式提示
        function hideAddModeTip() {
            const tip = document.getElementById('addModeTip');
            if (tip && tip.parentNode) {
                tip.parentNode.removeChild(tip);
            }
        }
        
        // 显示添加途经点对话框
        function showAddPointDialog(lng, lat) {
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                padding: 20px;
            `;
            
            modal.innerHTML = `
                <div style="
                    background: white;
                    border-radius: 16px;
                    padding: 24px;
                    max-width: 400px;
                    width: 100%;
                    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
                ">
                    <h3 style="margin: 0 0 16px 0; color: #1f2937; text-align: center;">➕ 添加途经点</h3>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">地点名称</label>
                        <input type="text" id="pointName" placeholder="请输入地点名称" style="
                            width: 100%;
                            padding: 8px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                        ">
                    </div>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">时间安排</label>
                        <input type="text" id="pointTime" placeholder="例如: 15:30" style="
                            width: 100%;
                            padding: 8px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                        ">
                    </div>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">地点描述</label>
                        <textarea id="pointDescription" placeholder="请输入地点描述" style="
                            width: 100%;
                            padding: 8px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                            height: 60px;
                            resize: vertical;
                        "></textarea>
                    </div>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">地点类型</label>
                        <select id="pointType" style="
                            width: 100%;
                            padding: 8px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                        ">
                            <option value="attraction">🏛️ 景点</option>
                            <option value="meal">🍜 用餐</option>
                            <option value="shopping">🛍️ 购物</option>
                            <option value="rest">☕ 休息</option>
                            <option value="other">📍 其他</option>
                        </select>
                    </div>
                    
                    <div style="font-size: 12px; color: #6b7280; margin-bottom: 16px;">
                        坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}
                    </div>
                    
                    <div style="display: flex; gap: 12px;">
                        <button onclick="addCustomPoint(${lng}, ${lat}); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #0ea5e9;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                        ">
                            ✅ 添加
                        </button>
                        <button onclick="this.closest('.modal').remove()" style="
                            flex: 1;
                            background: #6b7280;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                        ">
                            ❌ 取消
                        </button>
                    </div>
                </div>
            `;
            
            modal.className = 'modal';
            document.body.appendChild(modal);
            
            // 点击背景关闭
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        }
        
        // 添加自定义途经点
        function addCustomPoint(lng, lat) {
            const name = document.getElementById('pointName').value.trim();
            const time = document.getElementById('pointTime').value.trim();
            const description = document.getElementById('pointDescription').value.trim();
            const type = document.getElementById('pointType').value;
            
            if (!name) {
                alert('请输入地点名称');
                return;
            }
            
            // 创建新的途经点
            const newPoint = {
                id: `custom-${Date.now()}`,
                name: name,
                time: time || '待定',
                description: description || '自定义途经点',
                coordinates: [lng, lat],
                type: type,
                status: 'pending',
                isCustom: true
            };
            
            // 添加到自定义列表
            customItinerary.push(newPoint);
            
            // 创建地图标记
            createCustomMarker(newPoint);
            
            // 更新时间轴
            updateTimeline();
            
            // 显示成功提示
            showSuccessTip(`✅ 已添加途经点: ${name}`);
        }
        
        // 创建自定义标记
        function createCustomMarker(point) {
            const typeIcons = {
                attraction: '🏛️',
                meal: '🍜',
                shopping: '🛍️',
                rest: '☕',
                other: '📍'
            };
            
            const colors = {
                attraction: '#8b5cf6',
                meal: '#f59e0b',
                shopping: '#ec4899',
                rest: '#06b6d4',
                other: '#6b7280'
            };
            
            const icon = typeIcons[point.type] || '📍';
            const color = colors[point.type] || '#6b7280';
            
            const markerContent = `
                <div style="
                    width: 50px;
                    height: 50px;
                    background: white;
                    border: 3px solid ${color};
                    border-radius: 50%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    font-weight: bold;
                    font-size: 12px;
                    color: ${color};
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                    cursor: pointer;
                    transition: all 0.3s ease;
                    position: relative;
                " onmouseover="this.style.transform='scale(1.2); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25)'" 
                   onmouseout="this.style.transform='scale(1); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15)'"
                   onclick="showCustomPointDetails('${point.id}')">
                    <div style="font-size: 16px; margin-bottom: 2px;">${icon}</div>
                    <div style="font-size: 10px; font-weight: bold;">+</div>
                    <div style="position: absolute; top: -5px; right: -5px; width: 12px; height: 12px; background: #10b981; border-radius: 50%; border: 2px solid white;"></div>
                </div>
            `;
            
            const marker = new AMap.Marker({
                position: point.coordinates,
                content: markerContent,
                title: point.name
            });
            
            marker.setMap(map);
            customMarkers.push(marker);
        }
        
        // 显示自定义点详情
        function showCustomPointDetails(pointId) {
            const point = customItinerary.find(p => p.id === pointId);
            if (point) {
                showLocationDetails(point.name, point);
            }
        }
        
        // 更新时间轴
        function updateTimeline() {
            const timeline = document.getElementById('timeline');
            if (!timeline) return;
            
            // 添加自定义途经点到时间轴
            const customPointsHtml = customItinerary.map(point => `
                <div class="timeline-item" data-location="${point.name}" data-time="${point.time}" onclick="centerOnLocation('${point.name}')">
                    <div class="timeline-time">${point.time}</div>
                    <div class="timeline-content">
                        <div class="timeline-title-text">${point.name}</div>
                        <div class="timeline-desc">${point.description}</div>
                    </div>
                </div>
            `).join('');
            
            // 在原有时间轴后添加自定义点
            const existingItems = timeline.querySelectorAll('.timeline-item:not([data-location])');
            if (existingItems.length > 0) {
                const lastItem = existingItems[existingItems.length - 1];
                lastItem.insertAdjacentHTML('afterend', customPointsHtml);
            }
        }
        
        // 显示成功提示
        function showSuccessTip(message) {
            const tip = document.createElement('div');
            tip.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #10b981;
                color: white;
                padding: 12px 16px;
                border-radius: 8px;
                font-size: 14px;
                z-index: 10000;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            `;
            tip.textContent = message;
            document.body.appendChild(tip);
            
            // 3秒后自动隐藏
            setTimeout(() => {
                if (tip.parentNode) {
                    tip.parentNode.removeChild(tip);
                }
            }, 3000);
        }
        
        // 地图点击事件（用于POI搜索）
        function onMapClickForPOI(e) {
            // 如果正在添加模式，不处理POI搜索
            if (isAddMode) return;
            
            const lng = e.lnglat.lng;
            const lat = e.lnglat.lat;
            
            // 搜索点击位置附近的POI
            searchNearbyPOI(lng, lat);
        }
        
        // 搜索附近POI
        async function searchNearbyPOI(lng, lat) {
            try {
                const url = `https://restapi.amap.com/v3/place/around?location=${lng},${lat}&radius=500&key=自己的Key&extensions=all`;
                const response = await fetch(url);
                const data = await response.json();
                
                if (data.status === '1' && data.pois && data.pois.length > 0) {
                    // 显示最近的POI信息
                    const nearestPOI = data.pois[0];
                    showPOIInfo(nearestPOI, lng, lat);
                } else {
                    // 如果没有找到POI，尝试关键字搜索
                    searchPOIByKeyword(lng, lat);
                }
            } catch (error) {
                console.error('搜索POI失败:', error);
                showErrorTip('搜索地点信息失败');
            }
        }
        
        // 通过关键字搜索POI
        async function searchPOIByKeyword(lng, lat) {
            try {
                // 使用周边搜索，搜索各种类型的POI
                const url = `https://restapi.amap.com/v3/place/around?location=${lng},${lat}&radius=1000&types=风景名胜|餐饮服务|购物服务|生活服务|商务住宅&key=自己的Key&extensions=all`;
                const response = await fetch(url);
                const data = await response.json();
                
                if (data.status === '1' && data.pois && data.pois.length > 0) {
                    const nearestPOI = data.pois[0];
                    showPOIInfo(nearestPOI, lng, lat);
                } else {
                    showErrorTip('未找到附近的地点信息');
                }
            } catch (error) {
                console.error('关键字搜索POI失败:', error);
                showErrorTip('搜索地点信息失败');
            }
        }
        
        // 显示POI信息
        function showPOIInfo(poi, lng, lat) {
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                padding: 20px;
            `;
            
            // 格式化地址
            const address = poi.address || '地址信息暂无';
            const phone = poi.tel || '暂无电话';
            const website = poi.website || '暂无网站';
            const rating = poi.biz_ext && poi.biz_ext.rating ? poi.biz_ext.rating : '暂无评分';
            const cost = poi.biz_ext && poi.biz_ext.cost ? poi.biz_ext.cost : '暂无价格信息';
            
            modal.innerHTML = `
                <div style="
                    background: white;
                    border-radius: 16px;
                    padding: 24px;
                    max-width: 500px;
                    width: 100%;
                    max-height: 80vh;
                    overflow-y: auto;
                    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
                    position: relative;
                ">
                    <button onclick="this.closest('.modal').remove()" style="
                        position: absolute;
                        top: 16px;
                        right: 16px;
                        background: #f3f4f6;
                        border: none;
                        width: 32px;
                        height: 32px;
                        border-radius: 50%;
                        cursor: pointer;
                        font-size: 18px;
                        color: #6b7280;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    ">×</button>
                    
                    <div style="text-align: center; margin-bottom: 20px;">
                        <div style="font-size: 48px; margin-bottom: 8px;">🏛️</div>
                        <h2 style="margin: 0 0 4px 0; color: #1f2937; font-size: 20px;">${poi.name}</h2>
                        <div style="
                            display: inline-block;
                            background: #0ea5e9;
                            color: white;
                            padding: 4px 12px;
                            border-radius: 20px;
                            font-size: 12px;
                            font-weight: 600;
                        ">${poi.type || '地点'}</div>
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <div style="display: flex; align-items: flex-start; margin-bottom: 12px;">
                            <span style="font-size: 16px; margin-right: 8px; margin-top: 2px;">📍</span>
                            <div>
                                <div style="font-size: 14px; color: #6b7280; line-height: 1.5;">${address}</div>
                                <div style="font-size: 12px; color: #9ca3af; margin-top: 4px;">坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}</div>
                            </div>
                        </div>
                        
                        ${phone !== '暂无电话' ? `
                        <div style="display: flex; align-items: center; margin-bottom: 12px;">
                            <span style="font-size: 16px; margin-right: 8px;">📞</span>
                            <span style="font-size: 14px; color: #6b7280;">${phone}</span>
                        </div>
                        ` : ''}
                        
                        ${website !== '暂无网站' ? `
                        <div style="display: flex; align-items: center; margin-bottom: 12px;">
                            <span style="font-size: 16px; margin-right: 8px;">🌐</span>
                            <a href="${website}" target="_blank" style="font-size: 14px; color: #0ea5e9; text-decoration: none;">${website}</a>
                        </div>
                        ` : ''}
                        
                        ${rating !== '暂无评分' ? `
                        <div style="display: flex; align-items: center; margin-bottom: 12px;">
                            <span style="font-size: 16px; margin-right: 8px;">⭐</span>
                            <span style="font-size: 14px; color: #6b7280;">评分: ${rating}</span>
                        </div>
                        ` : ''}
                        
                        ${cost !== '暂无价格信息' ? `
                        <div style="display: flex; align-items: center; margin-bottom: 12px;">
                            <span style="font-size: 16px; margin-right: 8px;">💰</span>
                            <span style="font-size: 14px; color: #6b7280;">人均: ${cost}</span>
                        </div>
                        ` : ''}
                    </div>
                    
                    <div style="display: flex; gap: 12px;">
                        <button onclick="navigateToPOI('${poi.location}'); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #0ea5e9;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 8px;
                        ">
                            🗺️ 导航
                        </button>
                        <button onclick="centerOnPOI('${poi.location}'); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #10b981;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 8px;
                        ">
                            🎯 居中
                        </button>
                    </div>
                </div>
            `;
            
            modal.className = 'modal';
            document.body.appendChild(modal);
            
            // 点击背景关闭
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        }
        
        // 导航到POI
        function navigateToPOI(location) {
            const [lng, lat] = location.split(',').map(Number);
            const url = `https://uri.amap.com/navigation?to=${lng},${lat}&src=苏州旅行助手`;
            window.open(url, '_blank');
        }
        
        // 居中到POI
        function centerOnPOI(location) {
            const [lng, lat] = location.split(',').map(Number);
            map.setCenter([lng, lat]);
            map.setZoom(16);
        }
        
        // 显示错误提示
        function showErrorTip(message) {
            const tip = document.createElement('div');
            tip.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #ef4444;
                color: white;
                padding: 12px 16px;
                border-radius: 8px;
                font-size: 14px;
                z-index: 10000;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            `;
            tip.textContent = message;
            document.body.appendChild(tip);
            
            // 3秒后自动隐藏
            setTimeout(() => {
                if (tip.parentNode) {
                    tip.parentNode.removeChild(tip);
                }
            }, 3000);
        }
        
        // 显示添加途经点对话框
        function showAddWaypointDialog(lnglat, startItem, endItem) {
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                padding: 20px;
            `;
            
            modal.innerHTML = `
                <div style="
                    background: white;
                    border-radius: 16px;
                    padding: 24px;
                    max-width: 600px;
                    width: 100%;
                    max-height: 90vh;
                    overflow-y: auto;
                    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
                ">
                    <h3 style="margin: 0 0 16px 0; color: #1f2937; text-align: center;">➕ 添加途经点</h3>
                    
                    <div style="margin-bottom: 16px; padding: 12px; background: #f8fafc; border-radius: 8px;">
                        <div style="font-size: 14px; color: #6b7280; margin-bottom: 4px;">路线信息</div>
                        <div style="font-size: 16px; font-weight: 600; color: #1f2937;">
                            ${startItem.name} → ${endItem.name}
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">搜索地点</label>
                        <div style="display: flex; gap: 8px; margin-bottom: 8px;">
                            <input type="text" id="searchInput" placeholder="搜索地点名称，如：寒山寺" style="
                                flex: 1;
                                padding: 8px 12px;
                                border: 1px solid #d1d5db;
                                border-radius: 6px;
                                font-size: 14px;
                            ">
                            <button onclick="searchPOI()" style="
                                background: #0ea5e9;
                                color: white;
                                border: none;
                                padding: 8px 16px;
                                border-radius: 6px;
                                font-size: 14px;
                                font-weight: 600;
                                cursor: pointer;
                            ">🔍 搜索</button>
                        </div>
                        <div id="searchResults" style="
                            max-height: 200px;
                            overflow-y: auto;
                            border: 1px solid #e5e7eb;
                            border-radius: 6px;
                            background: white;
                            display: none;
                        "></div>
                    </div>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">途经点名称</label>
                        <input type="text" id="waypointName" placeholder="请输入途经点名称" style="
                            width: 100%;
                            padding: 8px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                        ">
                    </div>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">途经点描述</label>
                        <textarea id="waypointDescription" placeholder="请输入途经点描述" style="
                            width: 100%;
                            padding: 8px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                            height: 60px;
                            resize: vertical;
                        "></textarea>
                    </div>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">途经点类型</label>
                        <select id="waypointType" style="
                            width: 100%;
                            padding: 8px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                        ">
                            <option value="attraction">🏛️ 景点</option>
                            <option value="meal">🍜 用餐</option>
                            <option value="shopping">🛍️ 购物</option>
                            <option value="rest">☕ 休息</option>
                            <option value="other">📍 其他</option>
                        </select>
                    </div>
                    
                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 4px; font-weight: 600; color: #374151;">位置选择</label>
                        <div style="display: flex; gap: 8px; margin-bottom: 8px;">
                            <button onclick="enableMapClick()" id="mapClickBtn" style="
                                flex: 1;
                                background: #10b981;
                                color: white;
                                border: none;
                                padding: 8px 16px;
                                border-radius: 6px;
                                font-size: 14px;
                                font-weight: 600;
                                cursor: pointer;
                            ">📍 点击地图选择</button>
                            <button onclick="useCurrentLocation()" style="
                                flex: 1;
                                background: #f59e0b;
                                color: white;
                                border: none;
                                padding: 8px 16px;
                                border-radius: 6px;
                                font-size: 14px;
                                font-weight: 600;
                                cursor: pointer;
                            ">🎯 使用当前位置</button>
                        </div>
                        <div id="locationInfo" style="
                            padding: 8px 12px;
                            background: #f0f9ff;
                            border-radius: 6px;
                            font-size: 12px;
                            color: #6b7280;
                        ">
                            坐标: ${lnglat.lng.toFixed(6)}, ${lnglat.lat.toFixed(6)}
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 12px;">
                        <button onclick="addWaypointAndPlan('${lnglat.lng}', '${lnglat.lat}', '${startItem.name}', '${endItem.name}'); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #0ea5e9;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                        ">
                            🗺️ 规划路线
                        </button>
                        <button onclick="this.closest('.modal').remove()" style="
                            flex: 1;
                            background: #6b7280;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                        ">
                            ❌ 取消
                        </button>
                    </div>
                </div>
            `;
            
            modal.className = 'modal';
            document.body.appendChild(modal);
            
            // 点击背景关闭
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
            
            // 存储当前对话框的引用
            window.currentWaypointModal = modal;
            window.currentStartItem = startItem;
            window.currentEndItem = endItem;
        }
        
        // 添加途经点并规划路线
        async function addWaypointAndPlan(lng, lat, startName, endName) {
            const name = document.getElementById('waypointName').value.trim();
            const description = document.getElementById('waypointDescription').value.trim();
            const type = document.getElementById('waypointType').value;
            
            if (!name) {
                alert('请输入途经点名称');
                return;
            }
            
            // 创建途经点
            const waypoint = {
                id: `waypoint-${Date.now()}`,
                name: name,
                description: description || '途经点',
                coordinates: [parseFloat(lng), parseFloat(lat)],
                type: type,
                status: 'pending',
                isWaypoint: true
            };
            
            // 保存当前路线状态到历史记录
            saveRouteState();
            
            // 规划新路线
            await planRouteWithWaypoint(startName, endName, waypoint);
        }
        
        // 保存路线状态
        function saveRouteState() {
            if (currentRoutePlan) {
                routeHistory.push(JSON.parse(JSON.stringify(currentRoutePlan)));
                // 限制历史记录数量
                if (routeHistory.length > 10) {
                    routeHistory.shift();
                }
            }
        }
        
        // 规划带途经点的路线
        async function planRouteWithWaypoint(startName, endName, waypoint) {
            try {
                const startItem = itineraryData.find(item => item.name === startName);
                const endItem = itineraryData.find(item => item.name === endName);
                
                if (!startItem || !endItem) {
                    showErrorTip('找不到起点或终点');
                    return;
                }
                
                // 显示规划中提示
                showPlanningTip('正在规划路线...');
                
                // 获取分段路线
                const route1 = await getDrivingRouteWithWaypoints(startItem.coordinates, waypoint.coordinates);
                const route2 = await getDrivingRouteWithWaypoints(waypoint.coordinates, endItem.coordinates);
                
                if (route1 && route2) {
                    // 确保距离和时间的单位正确
                    const distance1 = parseInt(route1.distance) || 0;
                    const distance2 = parseInt(route2.distance) || 0;
                    const duration1 = parseInt(route1.duration) || 0;
                    const duration2 = parseInt(route2.duration) || 0;
                    
                    console.log('路线1距离:', distance1, '米, 时间:', duration1, '秒');
                    console.log('路线2距离:', distance2, '米, 时间:', duration2, '秒');
                    
                    // 创建新的路线规划
                    currentRoutePlan = {
                        start: startItem,
                        waypoint: waypoint,
                        end: endItem,
                        route1: {
                            ...route1,
                            distance: distance1,
                            duration: duration1
                        },
                        route2: {
                            ...route2,
                            distance: distance2,
                            duration: duration2
                        },
                        totalDistance: distance1 + distance2,
                        totalDuration: duration1 + duration2
                    };
                    
                    // 显示路线规划结果
                    showRoutePlanResult();
                    
                    // 在地图上绘制新路线
                    drawPlannedRoute();
                } else {
                    showErrorTip('路线规划失败');
                }
            } catch (error) {
                console.error('路线规划失败:', error);
                showErrorTip('路线规划失败');
            }
        }
        
        // 获取带途经点的驾车路线
        async function getDrivingRouteWithWaypoints(origin, destination) {
            const url = `https://restapi.amap.com/v3/direction/driving?origin=${origin[0]},${origin[1]}&destination=${destination[0]},${destination[1]}&key=自己的Key&extensions=base`;
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.status === '1' && data.route && data.route.paths && data.route.paths.length > 0) {
                const path = data.route.paths[0];
                console.log('API返回的路线数据:', {
                    distance: path.distance,
                    duration: path.duration,
                    tolls: path.tolls
                });
                
                return {
                    distance: parseInt(path.distance) || 0,
                    duration: parseInt(path.duration) || 0,
                    cost: parseFloat(path.tolls) || 0,
                    steps: path.steps || []
                };
            }
            return null;
        }
        
        // 显示路线规划结果
        function showRoutePlanResult() {
            if (!currentRoutePlan) return;
            
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                padding: 20px;
            `;
            
            const totalDistance = formatDistance(currentRoutePlan.totalDistance);
            const totalDuration = formatDuration(currentRoutePlan.totalDuration);
            const totalCost = currentRoutePlan.route1.cost + currentRoutePlan.route2.cost;
            
            modal.innerHTML = `
                <div style="
                    background: white;
                    border-radius: 16px;
                    padding: 24px;
                    max-width: 600px;
                    width: 100%;
                    max-height: 80vh;
                    overflow-y: auto;
                    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
                ">
                    <h3 style="margin: 0 0 16px 0; color: #1f2937; text-align: center;">🗺️ 路线规划结果</h3>
                    
                    <div style="margin-bottom: 20px; padding: 16px; background: #f0f9ff; border-radius: 8px;">
                        <div style="font-size: 16px; font-weight: 600; color: #1f2937; margin-bottom: 8px;">
                            ${currentRoutePlan.start.name} → ${currentRoutePlan.waypoint.name} → ${currentRoutePlan.end.name}
                        </div>
                        <div style="display: flex; justify-content: space-between; font-size: 14px; color: #6b7280;">
                            <span>总距离: ${totalDistance}</span>
                            <span>总时间: ${totalDuration}</span>
                            <span>总费用: ¥${totalCost}</span>
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <div style="display: flex; align-items: center; margin-bottom: 12px; padding: 12px; background: #f8fafc; border-radius: 8px;">
                            <div style="width: 8px; height: 8px; background: #0ea5e9; border-radius: 50%; margin-right: 12px;"></div>
                            <div>
                                <div style="font-weight: 600; color: #1f2937;">${currentRoutePlan.start.name}</div>
                                <div style="font-size: 12px; color: #6b7280;">起点</div>
                            </div>
                        </div>
                        
                        <div style="display: flex; align-items: center; margin-bottom: 12px; padding: 12px; background: #f0fdf4; border-radius: 8px;">
                            <div style="width: 8px; height: 8px; background: #10b981; border-radius: 50%; margin-right: 12px;"></div>
                            <div>
                                <div style="font-weight: 600; color: #1f2937;">${currentRoutePlan.waypoint.name}</div>
                                <div style="font-size: 12px; color: #6b7280;">途经点 - ${formatDistance(currentRoutePlan.route1.distance)} - ${formatDuration(currentRoutePlan.route1.duration)}</div>
                            </div>
                        </div>
                        
                        <div style="display: flex; align-items: center; margin-bottom: 12px; padding: 12px; background: #f8fafc; border-radius: 8px;">
                            <div style="width: 8px; height: 8px; background: #6b7280; border-radius: 50%; margin-right: 12px;"></div>
                            <div>
                                <div style="font-weight: 600; color: #1f2937;">${currentRoutePlan.end.name}</div>
                                <div style="font-size: 12px; color: #6b7280;">终点 - ${formatDistance(currentRoutePlan.route2.distance)} - ${formatDuration(currentRoutePlan.route2.duration)}</div>
                            </div>
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 12px;">
                        <button onclick="confirmRoutePlan(); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #10b981;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                        ">
                            ✅ 确认路线
                        </button>
                        <button onclick="modifyRoutePlan(); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #f59e0b;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                        ">
                            ✏️ 修改路线
                        </button>
                        <button onclick="revertRoutePlan(); this.closest('.modal').remove();" style="
                            flex: 1;
                            background: #ef4444;
                            color: white;
                            border: none;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                        ">
                            ↩️ 回退
                        </button>
                    </div>
                </div>
            `;
            
            modal.className = 'modal';
            document.body.appendChild(modal);
            
            // 点击背景关闭
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
        }
        
        // 绘制规划的路线
        function drawPlannedRoute() {
            if (!currentRoutePlan) return;
            
            // 清除现有路线
            clearCurrentRoutes();
            
            // 绘制第一段路线
            if (currentRoutePlan.route1.steps && currentRoutePlan.route1.steps.length > 0) {
                const path1 = [];
                currentRoutePlan.route1.steps.forEach(step => {
                    if (step.polyline) {
                        const coords = step.polyline.split(';').map(coord => {
                            const [lng, lat] = coord.split(',');
                            return [parseFloat(lng), parseFloat(lat)];
                        });
                        path1.push(...coords);
                    }
                });
                
                const polyline1 = new AMap.Polyline({
                    path: path1,
                    strokeColor: '#0ea5e9',
                    strokeWeight: 4,
                    strokeOpacity: 0.8,
                    strokeStyle: 'solid'
                });
                polyline1.setMap(map);
            }
            
            // 绘制第二段路线
            if (currentRoutePlan.route2.steps && currentRoutePlan.route2.steps.length > 0) {
                const path2 = [];
                currentRoutePlan.route2.steps.forEach(step => {
                    if (step.polyline) {
                        const coords = step.polyline.split(';').map(coord => {
                            const [lng, lat] = coord.split(',');
                            return [parseFloat(lng), parseFloat(lat)];
                        });
                        path2.push(...coords);
                    }
                });
                
                const polyline2 = new AMap.Polyline({
                    path: path2,
                    strokeColor: '#10b981',
                    strokeWeight: 4,
                    strokeOpacity: 0.8,
                    strokeStyle: 'solid'
                });
                polyline2.setMap(map);
            }
            
            // 添加途经点标记
            const waypointMarker = new AMap.Marker({
                position: currentRoutePlan.waypoint.coordinates,
                content: `
                    <div style="
                        width: 40px;
                        height: 40px;
                        background: #10b981;
                        border: 3px solid white;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        color: white;
                        font-weight: bold;
                        font-size: 16px;
                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
                    ">📍</div>
                `,
                title: currentRoutePlan.waypoint.name
            });
            waypointMarker.setMap(map);
        }
        
        // 清除当前路线
        function clearCurrentRoutes() {
            // 这里可以添加清除现有路线的逻辑
            // 由于我们使用的是新的路线，暂时不实现清除功能
        }
        
        // 确认路线规划
        function confirmRoutePlan() {
            if (currentRoutePlan) {
                showSuccessTip('路线规划已确认');
                // 这里可以添加保存路线到行程的逻辑
            }
        }
        
        // 修改路线规划
        function modifyRoutePlan() {
            if (currentRoutePlan) {
                // 重新显示添加途经点对话框
                const startItem = currentRoutePlan.start;
                const endItem = currentRoutePlan.end;
                const waypoint = currentRoutePlan.waypoint;
                
                // 这里可以添加修改途经点的逻辑
                showSuccessTip('请重新选择途经点位置');
            }
        }
        
        // 回退路线规划
        function revertRoutePlan() {
            if (routeHistory.length > 0) {
                currentRoutePlan = routeHistory.pop();
                if (currentRoutePlan) {
                    showRoutePlanResult();
                    drawPlannedRoute();
                } else {
                    // 回退到原始路线
                    currentRoutePlan = null;
                    showSuccessTip('已回退到原始路线');
                    // 重新绘制原始路线
                    addRouteLines();
                }
            } else {
                showSuccessTip('没有可回退的路线');
            }
        }
        
        // 显示规划中提示
        function showPlanningTip(message) {
            const tip = document.createElement('div');
            tip.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 16px 24px;
                border-radius: 8px;
                font-size: 14px;
                z-index: 10000;
                text-align: center;
            `;
            tip.innerHTML = `
                <div style="margin-bottom: 8px;">🗺️ ${message}</div>
                <div style="width: 20px; height: 20px; border: 2px solid #0ea5e9; border-radius: 50%; margin: 0 auto; animation: spin 1s linear infinite;"></div>
            `;
            document.body.appendChild(tip);
            
            // 3秒后自动隐藏
            setTimeout(() => {
                if (tip.parentNode) {
                    tip.parentNode.removeChild(tip);
                }
            }, 3000);
        }
        
        // 搜索POI
        async function searchPOI() {
            const searchInput = document.getElementById('searchInput');
            const searchResults = document.getElementById('searchResults');
            const keyword = searchInput.value.trim();
            
            if (!keyword) {
                showErrorTip('请输入搜索关键词');
                return;
            }
            
            try {
                // 显示搜索中状态
                searchResults.innerHTML = '<div style="padding: 12px; text-align: center; color: #6b7280;">🔍 搜索中...</div>';
                searchResults.style.display = 'block';
                
                // 搜索POI
                const config = window.AppConfig;
                const url = `${config.amap.baseUrl}/v3/place/text?keywords=${encodeURIComponent(keyword)}&city=${config.api.weather.city}&key=${config.amap.key}&extensions=all`;
                const response = await fetch(url);
                const data = await response.json();
                
                if (data.status === '1' && data.pois && data.pois.length > 0) {
                    let html = '';
                    data.pois.slice(0, 10).forEach((poi, index) => {
                        const address = poi.address || '地址信息暂无';
                        const distance = poi.distance ? `距离: ${(poi.distance / 1000).toFixed(1)}km` : '';
                        
                        html += `
                            <div onclick="selectPOI('${poi.location}', '${poi.name.replace(/'/g, "\\'")}', '${address.replace(/'/g, "\\'")}')" style="
                                padding: 12px;
                                border-bottom: 1px solid #e5e7eb;
                                cursor: pointer;
                                transition: background-color 0.2s;
                            " onmouseover="this.style.backgroundColor='#f8fafc'" onmouseout="this.style.backgroundColor='white'">
                                <div style="font-weight: 600; color: #1f2937; margin-bottom: 4px;">${poi.name}</div>
                                <div style="font-size: 12px; color: #6b7280; margin-bottom: 2px;">${address}</div>
                                <div style="font-size: 11px; color: #9ca3af;">${distance} | ${poi.type || '地点'}</div>
                            </div>
                        `;
                    });
                    
                    searchResults.innerHTML = html;
                } else {
                    searchResults.innerHTML = '<div style="padding: 12px; text-align: center; color: #6b7280;">未找到相关地点</div>';
                }
            } catch (error) {
                console.error('搜索POI失败:', error);
                searchResults.innerHTML = '<div style="padding: 12px; text-align: center; color: #ef4444;">搜索失败，请重试</div>';
            }
        }
        
        // 选择POI
        function selectPOI(location, name, address) {
            const [lng, lat] = location.split(',').map(Number);
            
            // 更新表单
            document.getElementById('waypointName').value = name;
            document.getElementById('waypointDescription').value = address;
            
            // 更新位置信息
            updateLocationInfo(lng, lat);
            
            // 隐藏搜索结果
            document.getElementById('searchResults').style.display = 'none';
            
            // 更新规划按钮的坐标
            updatePlanButton(lng, lat);
        }
        
        // 启用地图点击选择
        function enableMapClick() {
            const mapClickBtn = document.getElementById('mapClickBtn');
            
            if (mapClickBtn.textContent.includes('选择中')) {
                // 取消地图点击模式
                mapClickBtn.textContent = '📍 点击地图选择';
                mapClickBtn.style.background = '#10b981';
                mapClickBtn.style.color = 'white';
                
                // 移除地图点击事件监听
                if (window.mapClickHandler) {
                    map.off('click', window.mapClickHandler);
                    window.mapClickHandler = null;
                }
                
                showSuccessTip('已取消地图点击选择模式');
            } else {
                // 启用地图点击模式
                mapClickBtn.textContent = '📍 选择中...';
                mapClickBtn.style.background = '#ef4444';
                mapClickBtn.style.color = 'white';
                
                // 添加地图点击事件监听
                window.mapClickHandler = function(e) {
                    const lng = e.lnglat.lng;
                    const lat = e.lnglat.lat;
                    
                    // 更新位置信息
                    updateLocationInfo(lng, lat);
                    
                    // 更新规划按钮的坐标
                    updatePlanButton(lng, lat);
                    
                    // 恢复按钮状态
                    mapClickBtn.textContent = '📍 点击地图选择';
                    mapClickBtn.style.background = '#10b981';
                    mapClickBtn.style.color = 'white';
                    
                    // 移除事件监听
                    map.off('click', window.mapClickHandler);
                    window.mapClickHandler = null;
                    
                    showSuccessTip('位置已选择');
                };
                
                map.on('click', window.mapClickHandler);
                showSuccessTip('请在地图上点击选择位置');
            }
        }
        
        // 使用当前位置
        function useCurrentLocation() {
            if (navigator.geolocation) {
                showSuccessTip('正在获取当前位置...');
                
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        const lng = position.coords.longitude;
                        const lat = position.coords.latitude;
                        
                        // 更新位置信息
                        updateLocationInfo(lng, lat);
                        
                        // 更新规划按钮的坐标
                        updatePlanButton(lng, lat);
                        
                        showSuccessTip('当前位置已获取');
                    },
                    function(error) {
                        console.error('获取位置失败:', error);
                        showErrorTip('获取当前位置失败，请手动选择位置');
                    }
                );
            } else {
                showErrorTip('浏览器不支持定位功能');
            }
        }
        
        // 更新位置信息显示
        function updateLocationInfo(lng, lat) {
            const locationInfo = document.getElementById('locationInfo');
            locationInfo.innerHTML = `
                坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}
                <div style="margin-top: 4px; font-size: 11px; color: #10b981;">✓ 位置已选择</div>
            `;
        }
        
        // 更新规划按钮的坐标
        function updatePlanButton(lng, lat) {
            const planButton = document.querySelector('button[onclick*="addWaypointAndPlan"]');
            if (planButton) {
                const startName = window.currentStartItem ? window.currentStartItem.name : '';
                const endName = window.currentEndItem ? window.currentEndItem.name : '';
                planButton.setAttribute('onclick', `addWaypointAndPlan('${lng}', '${lat}', '${startName}', '${endName}'); this.closest('.modal').remove();`);
            }
        }
        
        // 加载行程数据
        async function loadItineraryData() {
            try {
                const savedItinerary = await window.dbManager.getItinerary();
                if (savedItinerary && savedItinerary.length > 0) {
                    itineraryData = savedItinerary;
                    console.log('从数据库加载行程数据:', itineraryData);
                } else {
                    // 保存默认行程数据到数据库
                    await window.dbManager.saveItinerary(itineraryData);
                    console.log('保存默认行程数据到数据库');
                }
            } catch (error) {
                console.error('加载行程数据失败:', error);
            }
        }
        
        // 加载路线管理界面
        function loadRouteManagement() {
            // 添加路线管理按钮到控制面板
            const controls = document.querySelector('.controls');
            if (controls) {
                const routeBtn = document.createElement('button');
                routeBtn.className = 'control-btn';
                routeBtn.innerHTML = '🗺️ 路线管理';
                routeBtn.onclick = showRouteManagement;
                controls.appendChild(routeBtn);
            }
        }
        
        // 显示路线管理界面
        async function showRouteManagement() {
            try {
                const routes = await window.dbManager.getRoutes();
                const activeRoute = await window.dbManager.getActiveRoute();
                
                const modal = document.createElement('div');
                modal.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 10000;
                    padding: 20px;
                `;
                
                let routesHtml = '';
                if (routes.length > 0) {
                    routes.forEach(route => {
                        const isActive = activeRoute && activeRoute.id === route.id;
                        const totalDistance = formatDistance(route.total_distance);
                        const totalDuration = formatDuration(route.total_duration);
                        
                        routesHtml += `
                            <div style="
                                padding: 16px;
                                border: 1px solid #e5e7eb;
                                border-radius: 8px;
                                margin-bottom: 12px;
                                background: ${isActive ? '#f0f9ff' : 'white'};
                                border-color: ${isActive ? '#0ea5e9' : '#e5e7eb'};
                            ">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                                    <h4 style="margin: 0; color: #1f2937;">${route.name}</h4>
                                    <div style="display: flex; gap: 8px;">
                                        ${!isActive ? `
                                            <button onclick="setActiveRoute(${route.id}); this.closest('.modal').remove();" style="
                                                background: #0ea5e9;
                                                color: white;
                                                border: none;
                                                padding: 4px 8px;
                                                border-radius: 4px;
                                                font-size: 12px;
                                                cursor: pointer;
                                            ">设为当前</button>
                                        ` : `
                                            <span style="
                                                background: #10b981;
                                                color: white;
                                                padding: 4px 8px;
                                                border-radius: 4px;
                                                font-size: 12px;
                                            ">当前路线</span>
                                        `}
                                        <button onclick="deleteRoute(${route.id}); this.closest('.modal').remove();" style="
                                            background: #ef4444;
                                            color: white;
                                            border: none;
                                            padding: 4px 8px;
                                            border-radius: 4px;
                                            font-size: 12px;
                                            cursor: pointer;
                                        ">删除</button>
                                    </div>
                                </div>
                                <div style="font-size: 14px; color: #6b7280; margin-bottom: 4px;">
                                    ${route.start_name} → ${route.end_name}
                                </div>
                                <div style="font-size: 12px; color: #9ca3af;">
                                    距离: ${totalDistance} | 时间: ${totalDuration} | 费用: ¥${route.total_cost}
                                </div>
                                <div style="font-size: 11px; color: #9ca3af; margin-top: 4px;">
                                    创建时间: ${new Date(route.created_at).toLocaleString()}
                                </div>
                            </div>
                        `;
                    });
                } else {
                    routesHtml = '<div style="text-align: center; color: #6b7280; padding: 20px;">暂无保存的路线</div>';
                }
                
                modal.innerHTML = `
                    <div style="
                        background: white;
                        border-radius: 16px;
                        padding: 24px;
                        max-width: 800px;
                        width: 100%;
                        max-height: 80vh;
                        overflow-y: auto;
                        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
                    ">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                            <div>
                                <h3 style="margin: 0; color: #1f2937;">🗺️ 路线管理</h3>
                                <p style="margin: 4px 0 0 0; color: #6b7280; font-size: 14px;">
                                    共 ${routes.length} 条路线 ${activeRoute ? '(当前路线已激活)' : ''}
                                </p>
                            </div>
                            <button onclick="this.closest('.modal').remove()" style="
                                background: #6b7280;
                                color: white;
                                border: none;
                                width: 32px;
                                height: 32px;
                                border-radius: 50%;
                                cursor: pointer;
                                font-size: 18px;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                            ">×</button>
                        </div>
                        
                        <div style="margin-bottom: 20px;">
                            <button onclick="saveCurrentRoute(); this.closest('.modal').remove();" style="
                                background: #10b981;
                                color: white;
                                border: none;
                                padding: 12px 16px;
                                border-radius: 8px;
                                font-size: 14px;
                                font-weight: 600;
                                cursor: pointer;
                                margin-right: 8px;
                            ">💾 保存当前路线</button>
                            <button onclick="saveAndReplaceRoute(); this.closest('.modal').remove();" style="
                                background: #f59e0b;
                                color: white;
                                border: none;
                                padding: 12px 16px;
                                border-radius: 8px;
                                font-size: 14px;
                                font-weight: 600;
                                cursor: pointer;
                                margin-right: 8px;
                            ">🔄 保存并替换旧路线</button>
                            <button onclick="clearAllRoutes(); this.closest('.modal').remove();" style="
                                background: #ef4444;
                                color: white;
                                border: none;
                                padding: 12px 16px;
                                border-radius: 8px;
                                font-size: 14px;
                                font-weight: 600;
                                cursor: pointer;
                            ">🗑️ 清空所有路线</button>
                        </div>
                        
                        <div style="max-height: 400px; overflow-y: auto;">
                            ${routesHtml}
                        </div>
                    </div>
                `;
                
                modal.className = 'modal';
                document.body.appendChild(modal);
                
                // 点击背景关闭
                modal.addEventListener('click', function(e) {
                    if (e.target === modal) {
                        modal.remove();
                    }
                });
                
            } catch (error) {
                console.error('加载路线管理失败:', error);
                showErrorTip('加载路线管理失败');
            }
        }
        
        // 保存当前路线
        async function saveCurrentRoute() {
            if (!currentRoutePlan) {
                showErrorTip('没有可保存的路线');
                return;
            }
            
            try {
                // 检查是否有现有路线
                const existingRoutes = await window.dbManager.getRoutes();
                const hasExistingRoutes = existingRoutes.length > 0;
                
                const routeName = prompt('请输入路线名称:', '苏州旅行路线');
                if (!routeName) return;
                
                // 如果有现有路线，询问是否删除旧路线
                let shouldDeleteOld = false;
                if (hasExistingRoutes) {
                    shouldDeleteOld = confirm(`发现 ${existingRoutes.length} 条旧路线，是否删除？\n\n点击"确定"删除所有旧路线\n点击"取消"保留旧路线`);
                }
                
                // 如果选择删除旧路线，先删除所有现有路线
                if (shouldDeleteOld) {
                    for (const route of existingRoutes) {
                        await window.dbManager.deleteRoute(route.id);
                    }
                    showSuccessTip(`已删除 ${existingRoutes.length} 条旧路线`);
                }
                
                const routeData = {
                    name: routeName,
                    start: currentRoutePlan.start,
                    end: currentRoutePlan.end,
                    waypoints: currentRoutePlan.waypoint ? [currentRoutePlan.waypoint] : [],
                    totalDistance: currentRoutePlan.totalDistance,
                    totalDuration: currentRoutePlan.totalDuration,
                    totalCost: (currentRoutePlan.route1.cost || 0) + (currentRoutePlan.route2.cost || 0),
                    isActive: true
                };
                
                const routeId = await window.dbManager.saveRoute(routeData);
                showSuccessTip('路线保存成功');
                
                // 重新加载路线管理界面
                showRouteManagement();
                
            } catch (error) {
                console.error('保存路线失败:', error);
                showErrorTip('保存路线失败');
            }
        }
        
        // 设置活跃路线
        async function setActiveRoute(routeId) {
            try {
                await window.dbManager.setActiveRoute(routeId);
                showSuccessTip('路线已设为当前路线');
                
                // 重新加载路线管理界面
                showRouteManagement();
                
            } catch (error) {
                console.error('设置活跃路线失败:', error);
                showErrorTip('设置活跃路线失败');
            }
        }
        
        // 删除路线
        async function deleteRoute(routeId) {
            if (!confirm('确定要删除这条路线吗？')) return;
            
            try {
                await window.dbManager.deleteRoute(routeId);
                showSuccessTip('路线已删除');
                
                // 重新加载路线管理界面
                showRouteManagement();
                
            } catch (error) {
                console.error('删除路线失败:', error);
                showErrorTip('删除路线失败');
            }
        }
        
        // 保存并替换旧路线
        async function saveAndReplaceRoute() {
            if (!currentRoutePlan) {
                showErrorTip('没有可保存的路线');
                return;
            }
            
            try {
                // 检查是否有现有路线
                const existingRoutes = await window.dbManager.getRoutes();
                
                if (existingRoutes.length === 0) {
                    // 没有旧路线，直接保存
                    await saveCurrentRoute();
                    return;
                }
                
                // 显示确认对话框
                const confirmed = confirm(`发现 ${existingRoutes.length} 条旧路线，确定要删除并替换为新路线吗？\n\n此操作不可恢复！`);
                if (!confirmed) return;
                
                const routeName = prompt('请输入新路线名称:', '苏州旅行路线');
                if (!routeName) return;
                
                // 删除所有旧路线
                for (const route of existingRoutes) {
                    await window.dbManager.deleteRoute(route.id);
                }
                
                // 保存新路线
                const routeData = {
                    name: routeName,
                    start: currentRoutePlan.start,
                    end: currentRoutePlan.end,
                    waypoints: currentRoutePlan.waypoint ? [currentRoutePlan.waypoint] : [],
                    totalDistance: currentRoutePlan.totalDistance,
                    totalDuration: currentRoutePlan.totalDuration,
                    totalCost: (currentRoutePlan.route1.cost || 0) + (currentRoutePlan.route2.cost || 0),
                    isActive: true
                };
                
                const routeId = await window.dbManager.saveRoute(routeData);
                showSuccessTip(`已删除 ${existingRoutes.length} 条旧路线，新路线保存成功`);
                
                // 重新加载路线管理界面
                showRouteManagement();
                
            } catch (error) {
                console.error('保存并替换路线失败:', error);
                showErrorTip('保存并替换路线失败');
            }
        }
        
        // 清空所有路线
        async function clearAllRoutes() {
            if (!confirm('确定要清空所有路线吗？此操作不可恢复！')) return;
            
            try {
                const routes = await window.dbManager.getRoutes();
                for (const route of routes) {
                    await window.dbManager.deleteRoute(route.id);
                }
                showSuccessTip('所有路线已清空');
                
                // 重新加载路线管理界面
                showRouteManagement();
                
            } catch (error) {
                console.error('清空路线失败:', error);
                showErrorTip('清空路线失败');
            }
        }
        
        // 获取天气信息
        function getWeatherInfo() {
            const config = window.AppConfig;
            const weatherUrl = `${config.amap.baseUrl}/v3/weather/weatherInfo?key=${config.amap.key}&city=${config.api.weather.city}&extensions=${config.api.weather.extensions}`;
            
            fetch(weatherUrl)
                .then(response => response.json())
                .then(data => {
                    if (data.status === '1' && data.lives && data.lives.length > 0) {
                        const weather = data.lives[0];
                        document.getElementById('weatherTemp').textContent = `🌤️ ${weather.temperature}°C`;
                        document.getElementById('weatherDesc').textContent = `${weather.city} · ${weather.weather}`;
                        document.getElementById('weatherAdvice').textContent = getWeatherAdvice(parseInt(weather.temperature), weather.weather);
                    }
                })
                .catch(error => {
                    console.error('获取天气信息失败:', error);
                    document.getElementById('weatherTemp').textContent = '🌤️ 22°C';
                    document.getElementById('weatherDesc').textContent = '苏州 · 晴';
                    document.getElementById('weatherAdvice').textContent = '建议穿轻薄衣物';
                });
        }
        
        // 获取天气建议
        function getWeatherAdvice(temperature, condition) {
            if (temperature >= 25) return '建议穿轻薄衣物，注意防晒';
            if (temperature >= 20) return '建议穿长袖或薄外套';
            if (temperature >= 15) return '建议穿外套或毛衣';
            if (temperature >= 10) return '建议穿厚外套或羽绒服';
            return '建议穿厚羽绒服，注意保暖';
        }
        
        // 更新当前时间
        function updateCurrentTime() {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
            
            // 更新当前行程描述
            const currentItem = itineraryData.find(item => item.status === 'current');
            if (currentItem) {
                document.getElementById('currentDesc').textContent = 
                    `${currentItem.time} ${currentItem.name} - ${currentItem.description}`;
            }
        }
        
        // 控制按钮功能
        
        // 切换头部显示/隐藏
        function toggleHeader() {
            const header = document.getElementById('header');
            const toggleBtn = document.querySelector('.header-toggle');
            
            if (header.classList.contains('collapsed')) {
                header.classList.remove('collapsed');
                toggleBtn.textContent = '收起';
            } else {
                header.classList.add('collapsed');
                toggleBtn.textContent = '展开';
            }
        }
        
        // 切换时间轴显示/隐藏
        function toggleTimeline() {
            const timeline = document.getElementById('timeline');
            const toggleBtn = document.querySelector('.timeline-toggle');
            
            if (timeline.classList.contains('collapsed')) {
                timeline.classList.remove('collapsed');
                toggleBtn.textContent = '📅';
            } else {
                timeline.classList.add('collapsed');
                toggleBtn.textContent = '📅';
            }
        }
        
        function refreshWeather() {
            getWeatherInfo();
            alert('🌤️ 天气信息已刷新');
        }
        
        function centerMap() {
            map.setZoomAndCenter(12, [120.6186, 31.3108]);
        }
        
        // 时间轴点击事件
        document.querySelectorAll('.timeline-item').forEach(item => {
            item.addEventListener('click', function() {
                const location = this.getAttribute('data-location');
                const itineraryItem = itineraryData.find(item => item.name === location);
                if (itineraryItem) {
                    map.setCenter(itineraryItem.coordinates);
                    map.setZoom(15);
                    showLocationInfo(itineraryItem);
                }
            });
        });
        
        // 添加脉冲动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.1); }
                100% { transform: scale(1); }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
